import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyBinaryFile {
	
	public static void copyFileByteByByte(
			String sourceFileName, String destFileName) throws IOException {
		InputStream inputStream = new FileInputStream(sourceFileName);
		try {
			OutputStream outputStream = new FileOutputStream(destFileName);
			try {
				int nextByte;
				while ((nextByte = inputStream.read()) != -1){
					outputStream.write(nextByte);
				}
			} finally {
				outputStream.close();
			}
		} finally {
			inputStream.close();
		}
	}
	
	public static void copyFileWithBuffer(
			String sourceFileName, String destFileName) throws IOException {
		InputStream inputStream = new FileInputStream(sourceFileName);
		try {
			OutputStream outputStream = new FileOutputStream(destFileName);
			try {
				byte[] buffer = new byte[64 * 1024]; // 64 KB buffer
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1){
					outputStream.write(buffer, 0, bytesRead);
				}
			} finally {
				outputStream.close();
			}
		} finally {
			inputStream.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		copyFileByteByByte("pic.jpg", "pic-copy-slow.jpg");
		copyFileWithBuffer("pic.jpg", "pic-copy-fast.jpg");
	}

}
